package com.zychao.smex.web.UI;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zychao.smex.db.service.BusinessService;
import com.zychao.smex.po.Book;

import sun.misc.BASE64Encoder;

@SuppressWarnings("serial")
@WebServlet("/ListBookServlet")
public class ListBookServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		BusinessService service = new BusinessService();
		Map<String, Book> map = service.getAllBook();
		request.setAttribute("map", map);
		String token = TokenProcessor.getInstance().markToken();
		request.getSession().setAttribute("token", token);
		request.getRequestDispatcher("/WEB-INF/jsp/listBook.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	
}

class TokenProcessor {
	private TokenProcessor(){}
	
	private static final TokenProcessor instance = new TokenProcessor();
	
	public static TokenProcessor getInstance() {
		return instance;
	}
	
	public String markToken() {
		String token = (System.currentTimeMillis() + new Random().nextInt(9999999) + "");
		
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] md5 = md.digest(token.getBytes());
			
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} catch(NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex);
		}
	}
}
